import axios from 'axios'
import {
	notification
} from 'ant-design-vue';
import router from '@/router'
// import config from '../config'
import store from '@/store'
import {
	getToken,removeToken
} from '@/utils/token'

const config = require('../config')
console.log(config);

let baseURL = config.baseUrl[config.env]
console.log('当前接口环境:' + process.env.VUE_APP_API)
baseURL = config.baseUrl[process.env.VUE_APP_API||'test']

var defaultHttp = axios.create({
	baseURL: baseURL,
	timeout: 10000,
	headers: {
		'Content-Type': 'application/json'
	}
})

defaultHttp.interceptors.request.use(function (config) {
	// 在发送请求之前做些什么
	var token = getToken()
	if (!config.params) config.params = {}
	config.params.token = token
	return config
}, function (error) {
	// 对请求错误做些什么
	return Promise.reject(error)
})

// 添加响应拦截器
defaultHttp.interceptors.response.use(function (response) {
	// 对响应数据做点什么
	if (response.data.code == 401 || response.data.code == 403) {
		console.log('登录过期')
		notification.error({
			message: '未登录或登陆过期，请重新登录',
			description: ''
		})
		removeToken()
		router.push('/login')

		return Promise.reject(response.data)
	} else if (response.data.code != 0 && (response.data.code + '').length != 9) {
		notification.error({
			message: response.data.message || '未知错误',
			description: ''
		})
		return Promise.reject(response.data)
	}
	return response.data
}, function (error) {
	// 对响应错误做点什么
	console.log(error)
	if (!error.response) {
		notification.error({
			message: '服务器错误或未知错误',
			description: ''
		})
	}
	return Promise.reject(error)
})

export default defaultHttp
